package Pet.Management.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import Pet.Management.domain.dto.MessageDTO;
import Pet.Management.domain.entity.Message;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.MessageRepository;
import Pet.Management.repository.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Autowired
    private MessageRepository messageRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 获取用户消息列表
     */
    @GetMapping("/list/{userId}")
    public ResponseEntity<Map<String, Object>> getMessages(
            @PathVariable String userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String types) {
        
        // 验证userId是否有效
        if (userId == null || userId.isEmpty() || "undefined".equals(userId) || "null".equals(userId)) {
            return ResponseEntity.badRequest().body(createErrorResponse("无效的用户ID"));
        }
        
        Long userIdLong;
        try {
            userIdLong = Long.parseLong(userId);
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body(createErrorResponse("用户ID必须是数字"));
        }
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Message> messagePage;
        
        try {
            if (type != null && !type.isEmpty()) {
                // 按单一类型筛选
                messagePage = messageRepository.findByReceiverIdAndType(userIdLong, type, pageable);
            } else if (types != null && !types.isEmpty()) {
                // 按多个类型筛选
                String[] typeArray = types.split(",");
                List<String> typeList = Arrays.asList(typeArray);
                
                // 使用原生SQL查询，支持IN条件
                messagePage = messageRepository.findByReceiverIdAndTypeIn(userIdLong, typeList, pageable);
            } else {
                // 获取所有消息和公告
                messagePage = messageRepository.findUserMessagesAndAnnouncements(userIdLong, pageable);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("messages", messagePage.getContent());
            response.put("currentPage", messagePage.getNumber());
            response.put("totalItems", messagePage.getTotalElements());
            response.put("totalPages", messagePage.getTotalPages());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(createErrorResponse("获取消息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public ResponseEntity<Map<String, Object>> getUnreadCount(
            @RequestParam(required = false) Long userId,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        // 先验证用户身份
        User currentUser = authenticateUser(userId, token);
        if (currentUser == null) {
            return ResponseEntity.status(401).build();
        }
        
        long totalUnread = messageRepository.countByReceiverIdAndIsRead(currentUser.getId(), false);
        long systemUnread = messageRepository.countByReceiverIdAndTypeAndIsRead(
                currentUser.getId(), "system", false);
        long privateUnread = messageRepository.countByReceiverIdAndTypeAndIsRead(
                currentUser.getId(), "private", false);
        long likeUnread = messageRepository.countByReceiverIdAndTypeAndIsRead(
                currentUser.getId(), "like", false);
        long commentUnread = messageRepository.countByReceiverIdAndTypeAndIsRead(
                currentUser.getId(), "comment", false);
        
        Map<String, Object> response = new HashMap<>();
        response.put("total", totalUnread);
        response.put("system", systemUnread);
        response.put("private", privateUnread);
        response.put("like", likeUnread);
        response.put("comment", commentUnread);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取用户私信对话
     */
    @GetMapping("/conversation/{otherUserId}")
    public ResponseEntity<List<MessageDTO>> getConversation(
            @PathVariable Long otherUserId,
            @RequestParam(required = false) Long userId,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        // 先验证用户身份
        User currentUser = authenticateUser(userId, token);
        if (currentUser == null) {
            return ResponseEntity.status(401).build();
        }
        
        // 验证对方用户是否存在
        Optional<User> otherUserOpt = userRepository.findById(otherUserId);
        if (!otherUserOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        List<Message> conversation = messageRepository.findConversation(
                currentUser.getId(), otherUserId);
        
        List<MessageDTO> messageDTOs = conversation.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        // 自动将对话中接收到的消息标记为已读
        List<Long> unreadMessageIds = conversation.stream()
                .filter(m -> !m.getIsRead() && m.getReceiverId().equals(currentUser.getId()))
                .map(Message::getId)
                .collect(Collectors.toList());
        
        for (Long messageId : unreadMessageIds) {
            messageRepository.markAsRead(messageId, currentUser.getId());
        }
        
        return ResponseEntity.ok(messageDTOs);
    }
    
    /**
     * 发送消息
     */
    @PostMapping
    @Transactional
    public ResponseEntity<Message> sendMessage(@RequestBody Map<String, Object> payload) {
        Message message = new Message();
        message.setSenderId(Long.valueOf(payload.get("senderId").toString()));
        message.setReceiverId(Long.valueOf(payload.get("receiverId").toString()));
        message.setTitle((String) payload.get("title"));
        message.setContent((String) payload.get("content"));
        message.setType((String) payload.get("type"));
        message.setIsRead(false);
        
        // 处理额外信息
        @SuppressWarnings("unchecked")
        Map<String, Object> extra = (Map<String, Object>) payload.get("extra");
        if (extra != null) {
            try {
                message.setExtra(objectMapper.writeValueAsString(extra));
            } catch (Exception e) {
                message.setExtra("{}");
            }
        }
        
        Message savedMessage = messageRepository.save(message);
        return ResponseEntity.ok(savedMessage);
    }
    
    /**
     * 标记消息为已读
     */
    @PutMapping("/{id}/read")
    @Transactional
    public ResponseEntity<Void> markAsRead(
            @PathVariable Long id,
            @RequestParam Long userId) {
        
        messageRepository.markAsRead(id, userId);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 标记所有消息为已读
     */
    @PutMapping("/read-all")
    @Transactional
    public ResponseEntity<Void> markAllAsRead(@RequestParam Long userId) {
        messageRepository.markAllAsRead(userId);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 删除消息
     */
    @DeleteMapping("/{id}")
    @Transactional
    public ResponseEntity<Void> deleteMessage(@PathVariable Long id) {
        Optional<Message> message = messageRepository.findById(id);
        if (message.isPresent()) {
            messageRepository.delete(message.get());
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }
    
    /**
     * 批量删除消息
     */
    @DeleteMapping("/batch/{ids}")
    @Transactional
    public ResponseEntity<Void> batchDeleteMessages(@PathVariable String ids) {
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            try {
                messageRepository.deleteById(Long.parseLong(id));
            } catch (Exception e) {
                // 忽略删除失败的情况
            }
        }
        return ResponseEntity.ok().build();
    }
    
    /**
     * 向所有用户发送系统消息（仅管理员可用）
     */
    @PostMapping("/system")
    @Transactional
    public ResponseEntity<Map<String, Object>> sendSystemMessage(
            @RequestBody Map<String, Object> payload,
            @RequestParam(required = false) Long userId,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        // 先验证用户身份
        User admin = authenticateUser(userId, token);
        if (admin == null || admin.getIsAdmin() == null || admin.getIsAdmin() != 1) {
            return ResponseEntity.status(403).build();
        }
        
        String title = (String) payload.get("title");
        String content = (String) payload.get("content");
        
        // 获取所有普通用户
        List<User> users = userRepository.findAll().stream()
                .filter(user -> user.getIsAdmin() == null || user.getIsAdmin() == 0)
                .collect(Collectors.toList());
        
        List<Message> savedMessages = new ArrayList<>();
        
        for (User user : users) {
            Message message = new Message();
            message.setSenderId(admin.getId());
            message.setReceiverId(user.getId());
            message.setTitle(title);
            message.setContent(content);
            message.setType("system");
            message.setIsRead(false);
            
            savedMessages.add(messageRepository.save(message));
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("messagesSent", savedMessages.size());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取公告列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getNoticeList(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestHeader(value = "Authorization", required = false) String token,
            @RequestParam(required = false) Long userId) {

        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<Message> messagePage;

        // 验证用户身份
        User currentUser = authenticateUser(userId, token);
        boolean isAdmin = currentUser != null && currentUser.getIsAdmin() != null && currentUser.getIsAdmin() == 1;

        // 构建查询条件
        if (title != null && !title.isEmpty()) {
            if (status != null && !status.isEmpty()) {
                messagePage = messageRepository.findByTypeAndStatusAndTitleContaining("system", status, title, pageable);
            } else {
                messagePage = messageRepository.findByTypeAndTitleContaining("system", title, pageable);
            }
        } else {
            if (status != null && !status.isEmpty()) {
                messagePage = messageRepository.findByTypeAndStatus("system", status, pageable);
            } else {
                messagePage = messageRepository.findByType("system", pageable);
            }
        }

        // 如果不是管理员，过滤掉未发布的公告
        if (!isAdmin) {
            List<Message> filteredContent = messagePage.getContent().stream()
                .filter(message -> "1".equals(message.getStatus()))
                .collect(Collectors.toList());
            messagePage = new PageImpl<>(filteredContent, pageable, filteredContent.size());
        }

        Map<String, Object> response = new HashMap<>();
        response.put("rows", messagePage.getContent());
        response.put("total", messagePage.getTotalElements());

        return ResponseEntity.ok(response);
    }
    
    /**
     * 新增公告
     */
    @PostMapping("/notice")
    @Transactional
    public ResponseEntity<Message> addNotice(@RequestBody Map<String, Object> payload) {
        Message message = new Message();
        message.setTitle((String) payload.get("title"));
        message.setContent((String) payload.get("content"));
        message.setType("system");
        message.setIsRead(false);
        message.setStatus((String) payload.get("status")); // 设置状态（0-草稿，1-已发布）
        
        // 设置发送者为当前管理员
        message.setSenderId(1L); // 这里暂时hardcode为管理员ID 1
        
        // 处理额外信息
        Map<String, Object> extra = new HashMap<>();
        try {
            message.setExtra(objectMapper.writeValueAsString(extra));
        } catch (Exception e) {
            message.setExtra("{}");
        }
        
        Message savedMessage = messageRepository.save(message);
        return ResponseEntity.ok(savedMessage);
    }
    
    /**
     * 发布公告
     */
    @PutMapping("/publish/{id}")
    @Transactional
    public ResponseEntity<Message> publishNotice(@PathVariable Long id) {
        Optional<Message> messageOpt = messageRepository.findById(id);
        if (!messageOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Message message = messageOpt.get();
        message.setStatus("1"); // 设置为已发布状态
        
        Message publishedMessage = messageRepository.save(message);
        return ResponseEntity.ok(publishedMessage);
    }
    
    /**
     * 将Message实体转换为MessageDTO
     */
    private MessageDTO convertToDTO(Message message) {
        MessageDTO dto = new MessageDTO();
        dto.setId(message.getId());
        dto.setTitle(message.getTitle());
        dto.setContent(message.getContent());
        dto.setIsRead(message.getIsRead());
        dto.setTime(message.getCreateTime());
        dto.setType(message.getType());
        
        // 获取发送者信息
        Optional<User> senderOpt = userRepository.findById(message.getSenderId());
        if (senderOpt.isPresent()) {
            User sender = senderOpt.get();
            dto.setSender(sender.getUsername());
            dto.setSenderId(sender.getId());
            
            // 设置发送者头像
            String avatar = sender.getAvatar();
            if (avatar != null && !avatar.isEmpty()) {
                dto.addExtra("avatar", avatar);
            }
        }
        
        // 复制其他额外信息
        if (message.getExtra() != null) {
            try {
                @SuppressWarnings("unchecked")
                Map<String, Object> extraMap = objectMapper.readValue(message.getExtra(), Map.class);
                // 将所有值转换为字符串
                extraMap.forEach((key, value) -> {
                    if (value != null) {
                        dto.addExtra(key, value.toString());
                    }
                });
            } catch (Exception e) {
                // 如果解析失败，不添加额外信息
                System.err.println("解析消息额外信息失败: " + e.getMessage());
            }
        }
        
        return dto;
    }
    
    /**
     * 验证用户身份
     */
    private User authenticateUser(Long userId, String token) {
        // 先通过userId参数查找用户
        if (userId != null) {
            System.out.println("尝试使用userId=" + userId + "查找用户");
            Optional<User> userOpt = userRepository.findById(userId);
            if (userOpt.isPresent()) {
                System.out.println("通过userId找到用户: " + userOpt.get().getUsername());
                return userOpt.get();
            }
        }
        
        // 如果没有userId或找不到对应用户，再尝试使用token
        if (token == null || token.isEmpty()) {
            return null;
        }
        
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        try {
            // 尝试将token解析为用户ID
            Long tokenUserId = Long.parseLong(token);
            Optional<User> currentUser = userRepository.findById(tokenUserId);
            
            if (currentUser.isPresent()) {
                return currentUser.get();
            }
        } catch (NumberFormatException e) {
            // 如果token不是有效的用户ID，尝试按用户名查找
            Optional<User> currentUser = userRepository.findByUsername(token);
            if (currentUser.isPresent()) {
                return currentUser.get();
            }
        }
        
        return null;
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("error", true);
        response.put("message", message);
        response.put("messages", List.of());
        response.put("totalItems", 0);
        return response;
    }
} 